﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;

public class UIAtlasRefrences
{
    static string fullPath = Application.dataPath + "/Resources";

    [MenuItem("GameEditor/筛选超大尺寸图片", false, 80)]
    public static void FindMaxTexture()
    {
        Debug.Log("查找开始");
        string[] files = Directory.GetFiles(fullPath, "*.*", SearchOption.AllDirectories);
        foreach (string tmp in files)
        {
            Texture texture = AssetDatabase.LoadAssetAtPath<Texture>(GetRelativeAssetsPath(tmp));
            if (texture != null)
            {
                if (texture.width > 1024 || texture.height > 1024)
                {
                    Debug.Log(tmp + "图片尺寸不合法（单边超过1024）宽: " + texture.width + " 高: " + texture.height);
                }
            }
        }
        Debug.Log("查找结束");
    }

    [MenuItem("GameEditor/筛选超小尺寸图片", false, 80)]
    public static void FindMinTexture()
    {
        Debug.Log("查找开始");
        string[] files = Directory.GetFiles(fullPath, "*.*", SearchOption.AllDirectories);
        foreach (string tmp in files)
        {
            Texture texture = AssetDatabase.LoadAssetAtPath<Texture>(GetRelativeAssetsPath(tmp));
            if (texture != null)
            {
                if (texture.width < 512 || texture.height < 512)
                {
                    Debug.Log(tmp + "图片尺寸不合法（单边不足512）宽: " + texture.width + " 高: " + texture.height);
                }
            }
        }
        Debug.Log("查找结束");
    }

    [MenuItem("GameEditor/查找图集引用", false, 80)]
    public static void FindRefrences()
    {
        SerializationMode currentMode = EditorSettings.serializationMode;
        EditorSettings.serializationMode = SerializationMode.ForceText;
        string path = AssetDatabase.GetAssetPath(Selection.activeObject);

        if (!string.IsNullOrEmpty(path))
        {
            string guid = AssetDatabase.AssetPathToGUID(path);
            List<string> extensions = new List<string>() { ".prefab", ".mat", ".unity", ".asset" };
            string[] files = Directory.GetFiles(fullPath, "*.*", SearchOption.AllDirectories)
                .Where(s => extensions.Contains(Path.GetExtension(s).ToLower())).ToArray();

            int startIndex = 0; Debug.Log("查找开始");
            EditorApplication.update = () =>
            {
                string file = files[startIndex];
                bool isCancel = EditorUtility.DisplayCancelableProgressBar("查找中", file, startIndex * 1.0f / files.Length);
                if (Regex.IsMatch(File.ReadAllText(file), guid))
                {
                    Debug.Log(file, AssetDatabase.LoadAssetAtPath(GetRelativeAssetsPath(file), typeof(Object)));
                }

                startIndex++;
                if (isCancel || startIndex >= files.Length)
                {
                    EditorUtility.ClearProgressBar();
                    EditorApplication.update = null;
                    EditorSettings.serializationMode = currentMode;
                    startIndex = 0; Debug.Log("查找结束");
                }
            };

        }
    }

    [MenuItem("GameEditor/UIAtlas引用排查", false, 80)]
    public static void Find()
    {
        SerializationMode currentMode = EditorSettings.serializationMode;
        EditorSettings.serializationMode = SerializationMode.ForceText;

        List<string> allAtlas = new List<string>() { ".prefab" };
        string[] allatlasfiles = Directory.GetFiles(fullPath, "*.*", SearchOption.AllDirectories)
            .Where(s => allAtlas.Contains(Path.GetExtension(s).ToLower())).ToArray();

        List<string> allUI = new List<string>() { ".prefab" };
        string[] allFiles = Directory.GetFiles(fullPath, "*.*", SearchOption.AllDirectories)
            .Where(s => allUI.Contains(Path.GetExtension(s).ToLower())).ToArray();

        if (allFiles.Length <= 0)
        {
            Debug.Log("没有找到UI窗口，无法排查");
        }

        int startIndex = 0; Debug.Log("查找开始");
        EditorApplication.update = () =>
        {
            string file = allFiles[startIndex];
            bool isCancel = EditorUtility.DisplayCancelableProgressBar("查找中", file, startIndex * 1.0f / allFiles.Length);

            int count = 0;
            for (int i = 0; i < allatlasfiles.Length; i++)
            {
                string guid = AssetDatabase.AssetPathToGUID(GetRelativeAssetsPath(allatlasfiles[i]));
                if (Regex.IsMatch(File.ReadAllText(file), guid))
                {
                    count = count + 1;
                    //Debug.Log(GetRelativeAssetsPath(file));
                    Debug.Log(GetRelativeAssetsPath(allatlasfiles[i]));
                }
            }

            if (count >= 2)
            {
                Debug.LogError("UIAtlas依赖数大于等于2，请检查一下" + GetRelativeAssetsPath(file));
            }

            startIndex++;
            if (isCancel || startIndex >= allFiles.Length)
            {
                EditorUtility.ClearProgressBar();
                EditorApplication.update = null;
                EditorSettings.serializationMode = currentMode;
                startIndex = 0; Debug.Log("查找结束");
            }
        };
    }

    static string GetRelativeAssetsPath(string path)
    {
        string tempPath = Path.GetFullPath(Application.dataPath);
        return "Assets" + Path.GetFullPath(path).Replace(tempPath, "").Replace('\\', '/');
    }
}